package com.example.backend.controller;

import com.example.backend.model.LoginRequest;
import com.example.backend.model.User;
import com.example.backend.service.UserService;
import com.example.backend.utils.Response;
import com.example.backend.validate.ValidateStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService service;

    @PostMapping("/login")
    public Response<Integer> login(@RequestBody LoginRequest loginRequest, HttpSession session) {
        int result = service.login(loginRequest, session);
        return result != -1 ?
                Response.Ok("login success", result)
                : Response.Error("login failed", result);
    }

    @GetMapping("/login/code")
    public void createCode(HttpServletRequest request,
                           HttpServletResponse response,
                           HttpSession session) throws IOException {
        service.createCode(request, response, session);
    }

    @PostMapping("/register")
    public Response<Integer> register(@RequestBody User user) {
        int result = service.register(user);
        return result != -1 ?
                Response.Ok("register success", result)
                : Response.Error("register failed", result);
    }

    @PostMapping("/exit")
    public Response<Integer> exit(@RequestBody User user, HttpSession session) {
        int result = service.exit(user, session);
        return result != -1 ?
                Response.Ok("exit success", result)
                : Response.Error("exit failed", result);
    }
}
